package hr.koshnica.android.ui;

import java.util.StringTokenizer;

import hr.koshnica.android.R;
import hr.koshnica.android.database.KoshnicaContract;
import hr.koshnica.android.database.KoshnicaContract.Search;
import hr.koshnica.android.ui.search.LocDescActivity;

import android.app.SearchManager;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockListActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

public class SearchActivity extends SherlockListActivity {

    private static final String TAG = "SearchActivity";
    private TextView tvSearch;
    private LinearLayout searchBar;
    private ListView lv;  
    private Cursor mCrs;
    private ImageButton btnSearch;
    private MenuItem mMenuItem;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search);
        handleIntent(getIntent());

        final ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeButtonEnabled(true);
        setTitle(R.string.search_title);
        actionBar.setTitle(R.string.search_title);
        actionBar.setDisplayShowTitleEnabled(true);
        
        lv = (ListView) findViewById(R.id.ListView01); 

        lv.setOnItemClickListener(new OnItemClickListener()
		{
		    @Override
		    public void onItemClick(AdapterView<?> a, View view, int position, long id)
		    {
		    	TextView tv = (TextView)view.findViewById(R.id.valueRowSearch2);    	
		    	String path = (String)tv.getText();
		    	StringTokenizer tokens = new StringTokenizer(path, "/");
		    	String first = tokens.nextToken();
		    	String second = tokens.nextToken();
		    	System.out.println("first:" + first);
		    	System.out.println("second:" + second);		    	
		    	onShowItemDetails(second, first);
		    }
		});
		
		lv.setEmptyView(findViewById(R.id.linearLayoutSearch));
        
    }

    @Override
    protected void onNewIntent(Intent intent) {
        setIntent(intent);
        handleIntent(intent);
    }

    private void handleIntent(Intent intent) {
        if (intent == null) {
            return;
        }
        if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
            
            String query = intent.getStringExtra(SearchManager.QUERY);
            getSupportActionBar().setSubtitle("\"" + query + "\"");
            doMySearch(query);
        } else if (Intent.ACTION_VIEW.equals(intent.getAction())) {
           
        	String path = intent.getStringExtra("intent_extra_data_key");
        	String data = intent.getDataString() + "/" + intent.getStringExtra("intent_extra_data_key");
        	Uri uri = Uri.parse(data);       
            String id = uri.getLastPathSegment();
            path = uri.getPathSegments().get(0);
            onShowItemDetails(id, path);
            finish();
        }
    }

    private void doMySearch(String query) {
        Cursor searchResults = getContentResolver().query(Search.CONTENT_URI,
                null, null, new String[] {
                    query
                }, null);
        startManagingCursor(searchResults);
        String[] from = new String[] {            
   			 	Search.TITLE,	            
   				Search.OVERVIEW,
   				Search.EXTRA_DATA
        };
         
        int[] to = new int[] {
                R.id.textListRowSearch1, 
                R.id.textListRowSearch2,
                R.id.valueRowSearch
        };
        SimpleCursorAdapter resultsAdapter = new SimpleCursorAdapter(getApplicationContext(),
                R.layout.list_row_search, searchResults, from, to);
        
        setListAdapter(resultsAdapter);
        stopManagingCursor(searchResults);
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
    	
    	TextView tv = (TextView)v.findViewById(R.id.valueRowSearch);    	
    	String path = (String)tv.getText();
    	StringTokenizer tokens = new StringTokenizer(path, "/");
    	String first = tokens.nextToken();
    	String second = tokens.nextToken();
    	System.out.println("first:" + first);
    	System.out.println("second:" + second);
    	
        onShowItemDetails(second, first);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {    	
    	menu.add("Search")
        .setIcon(R.drawable.ic_search)
        .setActionView(R.layout.collapsible_edittext)
        .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
    	
    	mMenuItem = menu.getItem(0);
    	mMenuItem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
            @Override
            public boolean onMenuItemActionCollapse(MenuItem item) {
            	
			        
            	SimpleCursorAdapter resultsAdapter = new SimpleCursorAdapter(getApplicationContext(),			               
            			R.layout.list_row_search_2, null, null, null);			        
			        
            	lv.setAdapter(resultsAdapter);			        
            	if (tvSearch != null)
            		tvSearch.setText("");
			      
                return true;  // Return true to collapse action view
            }

            @Override
            public boolean onMenuItemActionExpand(MenuItem item) {
            	searchBar = (LinearLayout)item.getActionView();
            	tvSearch = (TextView)searchBar.findViewById(R.id.searchboxCollapsable);
            	tvSearch.addTextChangedListener(new TextWatcher(){
        			@Override
        			public void afterTextChanged(Editable s){
        				// Abstract Method of TextWatcher Interface.		
        			}	
        			@Override
        			public void beforeTextChanged(CharSequence s, int start, int count, int after) {	
        				// Abstract Method of TextWatcher Interface.		
        			}		
        			@Override
        			public void onTextChanged(CharSequence s, int start, int before, int count)	{	
        				String str = tvSearch.getText().toString();
        				System.out.println(str);			
        				
        				mCrs = getContentResolver().query(Search.CONTENT_URI,
        		                null, null, new String[] {
        	                    str
        	                }, null);
        				
        				 startManagingCursor(mCrs);
        			        String[] from = new String[] {            
        			   			 	Search.TITLE,	            
        			   				Search.OVERVIEW,
        			   				Search.EXTRA_DATA			   				
        			        };
        			         
        			        int[] to = new int[] {
        			                R.id.textListRowSearch21, 
        			                R.id.textListRowSearch22,
        			                R.id.valueRowSearch2			                
        			        };
        			        SimpleCursorAdapter resultsAdapter = new SimpleCursorAdapter(getApplicationContext(),
        			                R.layout.list_row_search_2, mCrs, from, to);
        			        
        			        lv.setAdapter(resultsAdapter);

        			        stopManagingCursor(mCrs);
        			}
        		});
            	
            	btnSearch = (ImageButton)searchBar.findViewById(R.id.searchbuttonCollapsable);
            	btnSearch.setOnClickListener(new OnClickListener() {
        			@Override
        			public void onClick(View v) {
        				System.out.println("println");
        				String term = tvSearch.getText().toString();
        				getSupportActionBar().setSubtitle("\"" + term + "\"");
        				doMySearch(term);
        				
        				SimpleCursorAdapter resultsAdapter = new SimpleCursorAdapter(getApplicationContext(),			               
                    			R.layout.list_row_search_2, null, null, null);			        
        			        
                    	lv.setAdapter(resultsAdapter);
                    	if (tvSearch != null)
                    		tvSearch.setText("");
                    	mMenuItem.collapseActionView();
        			}
        		});
            	           	
                return true;  // Return true to expand action view
            }
        });
    
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                final Intent intent = new Intent(this, MainActivityV2.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                
                SimpleCursorAdapter resultsAdapter = new SimpleCursorAdapter(getApplicationContext(),			               
    	     			R.layout.list_row_search_2, null, null, null);			        		        
    	     	lv.setAdapter(resultsAdapter);	
    	     	if (tvSearch != null)
    	     		tvSearch.setText("");
    	     	
                startActivity(intent); 
                return true;          
        }
        return super.onOptionsItemSelected(item);
    }

    private void onShowItemDetails(String id, String path) {
    	System.out.println("pozvan je onShowItemDetails");
    	if (path.equals(KoshnicaContract.PATH_LOCATIONS)) { 		
    		 Intent i = new Intent(this, LocDescActivity.class);
    	     i.putExtra("index", Integer.parseInt(id));
    	     
    	     SimpleCursorAdapter resultsAdapter = new SimpleCursorAdapter(getApplicationContext(),			               
 	     			R.layout.list_row_search_2, null, null, null);			        		        
 	     	 lv.setAdapter(resultsAdapter);
 	     	 if (tvSearch != null)
 	     		 tvSearch.setText("");
 	     	
    	     startActivity(i); 	         	
    	} else if (path.equals(KoshnicaContract.PATH_EVENTS)) { 
    		Intent i = new Intent(this, LocDescActivity.class);
   	     	i.putExtra("index", Integer.parseInt(id));
   	     	
	   	    SimpleCursorAdapter resultsAdapter = new SimpleCursorAdapter(getApplicationContext(),			               
	     			R.layout.list_row_search_2, null, null, null);			        		        
	     	lv.setAdapter(resultsAdapter);
	     	if (tvSearch != null)
	     		tvSearch.setText("");
     	
   	     	startActivity(i);
    	}          

    }
}